import sys
import os.path
import shutil
import os
import django
import csv

pro_dir = os.getcwd()
sys.path.append(pro_dir)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mitagger.settings")

from home.models import Image
from home.files import createFolder, getMetaInformation, convertFormat

def importErrorImage(errorfilename):
    f = open(errorfilename, 'r')
    error_image_list = dict()
    basePath = createFolder('image')
    for file_path in f.readlines():
        if file_path.endswith('\n'):
            file_path = file_path[:len(file_path)-1]
        if file_path.lower().endswith('tif'):
            filename = os.path.split(file_path)[1][0:-4]
            #print filename
            error_image_list[os.path.split(file_path)[1][0:-4]+'.tif'] = file_path
            #shutil.copyfile(file_path, basePath+filename)
    print 'total images: %d' % len(error_image_list)
    analyseCSVs('./images/Metadata', error_image_list)

def analyseCSVs(csvBasePath, error_image_list,):
    for parentDir, dirnames, filenames in os.walk(csvBasePath):
        for filename in filenames:
            if filename.lower().endswith('csv'):
                extractDataFromCSV(error_image_list, (parentDir if parentDir.endswith('/') else parentDir + '/') + filename)

def extractDataFromCSV(error_image_list, csvFilepath):
    csv_reader = csv.reader(open(csvFilepath, 'r'))
    indexDict = dict()
<<<<<<< HEAD
    print "processing file %s" % csvFilepath
=======
    #print "processing csv %s" % csvFilepath
>>>>>>> dfe896ae36cc60eff309dbe70ed573992e6c8a6d
    for i, row in enumerate(csv_reader):
        if i == 0:
            for j, item in enumerate(row):
                if 'FigFilename' in item or 'Fig_Filename' in item:
                    indexDict['filename'] = j
                elif 'Fig Title' in item or 'Fig_Title' in item:
                    indexDict['figTitle'] = j
                elif 'FigLegend' in item or 'Fig_Caption' in item:
                    indexDict['figLegend'] = j
                elif 'Article URI' in item or 'Article_URI' in item:
                    indexDict['articleURI'] = j
                elif 'FigLabel' in item or 'Fig_Label' in item:
                    indexDict['figLabel'] = j
                elif 'Article DOI' in item or 'Article_DOI' in item:
                    indexDict['articleDOI'] = j
        else:
            for j, item in enumerate(row):
                if j == indexDict['filename']:
<<<<<<< HEAD
                    if item in error_image_list:
                        print "saving image %s" % item
=======
                    print item
                    if item in error_image_list.keys():
                        print "processing file %s" % item
>>>>>>> dfe896ae36cc60eff309dbe70ed573992e6c8a6d
                        saveInfoToDB(row, indexDict, error_image_list)
                        del error_image_list[item]
                    break

def saveInfoToDB(infos, indexDict, error_image_list):
    infolist = list()
    for item in infos:
        infolist.append(item)
    newImage = Image(file_name=infolist[indexDict['filename']])
    newImage.title = infolist[indexDict['figTitle']]
    newImage.legend = infolist[indexDict['figLegend']]
    newImage.doi_link = infolist[indexDict['articleURI']]
    newImage.label = infolist[indexDict['figLabel']]
    newImage.relevant_articleDOI = infolist[indexDict['articleDOI']]
    newImage.image_file_location = error_image_list[infolist[indexDict['filename']]]
    try:
        newImage.save()
    except:
       print 'image %s error' % infolist[indexDict['filename']]




def mainFunc():
    errorfilename = 'unimport_images.txt'
    importErrorImage(errorfilename)

if __name__ == '__main__':
    django.setup()
    mainFunc()
